from db import utils
from logger import logger
from tools.file_searcher import FileSearcher
from sub_events.base_event import BaseEvent

LOGGER = logger.CustomLogger()

COMMENT_CHECK_TDD = "check tdd"
COMMENT_FORCE_TDD = "force tdd"


class CheckTddEvent(BaseEvent):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.event_name_zh: str = "TDD检查"
        self.event_name_en: str = "TDD check"

    def execute(self):
        tdd_exist = False
        try:
            params = {'access_token': self.get_admin_token()}
            files = self.git_client.get_filenames(self.hook.pr_number, params=params)
            whitelist = self.cfg.get("sub_events", {}).get("check_tdd", {}).get("check_tdd_whitelist", [])
            fs = FileSearcher(whitelist)
            files_not_in_whitelist = fs.check_and_get_invalid_files(files)
            if not files_not_in_whitelist:
                return
            for filename in files_not_in_whitelist:
                if "unittest" in filename:
                    tdd_exist = True
        except Exception as e:
            LOGGER.error(f"[{self.hook.pr_number}] get files failed, details: {str(e)}")
            return
        force_status = utils.get_force_pass_status_by_hook(self.hook, "tdd")
        self.failed = not tdd_exist and not force_status
        if self.failed:
            suggestion = "请自行检视是否需要补充用例或联系以下人员检视后评论\"%s\"强制通过。若最新提交中已携带TDD，请评论\"%s\"重新触发检查。\n" % (
                COMMENT_FORCE_TDD, COMMENT_CHECK_TDD)
            suggestion += ("Please:\n"
                           "    1. Commit with TDD implementation, then leave a \"%s\" comment to re-trigger "
                           "the TDD check process. or\n"
                           "    2. Contact the following members to leave a \"%s\" comment.\n") % (
                              COMMENT_CHECK_TDD, COMMENT_FORCE_TDD)
            for member, name in self.cfg.get("sub_events", {}).get("check_tdd", {}).get("force_accounts").items():
                suggestion += f"{name}: @{member.split('/')[-1]}\n"
            self.comment = suggestion
